﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;

namespace Hazop
{
    public partial class WorkPage : UserControl{

        private int _adviceCount = 0;

        public WorkPage(WorkNode workNode)
        {
            InitializeComponent();
            Program.Workspace.ColumnsChanged +=new Action<List<string>>(Workspace_ColumnsChanged);
            Program.Workspace.PidListChanged += new Action<Dictionary<string,string>>(Workspace_PidListChanged);
            dgvWorkArea.AllowUserToAddRows = false;
            guideWord.DataSource = Program.Workspace.GuideWordList;
//            BindingList<WorkNodeItem> list = new BindingList<WorkNodeItem>(new List<WorkNodeItem>());
//            dgvWorkArea.DataSource = list;
            HideColumns();
            _bindWorkNodeItems.DataSource = workNode.WorkNodeItemList;
            dgvWorkArea.DataSource = _bindWorkNodeItems;
            LoadData(workNode);
        }

        void Workspace_PidListChanged(Dictionary<string,string> dictionary){
            if (lblPidNum == null || lblPidNum.Text.Equals("")){
                return;
            }
            List<string> newPids = new List<string>();
            string[] oldPids = lblPidNum.Text.Split(new Char[]{','});
            foreach (string s in oldPids){
                if (dictionary.ContainsKey(s))
                {
                    newPids.Add(dictionary[s]);
                }
                else{
                    newPids.Add(s);
                }
            }
            string newText = string.Empty;
            foreach (string pid in newPids){
                newText += pid + ",";
            }
            newText = newText.Substring(0, newText.Length - 1);
            lblPidNum.Text = newText;
            SaveWithoutRemider();
        }

        private void HideColumns(){
            foreach (DataGridViewColumn column in dgvWorkArea.Columns)
            {
                if (Program.Workspace.GetHideColumns().Contains(column.HeaderText))
                {
                    column.Visible = false;
                }
                else
                {
                    column.Visible = true;
                }
            }
        }

        private void Workspace_ColumnsChanged(List<string> hideCols){
            foreach (DataGridViewColumn column in dgvWorkArea.Columns)
            {
                if (hideCols.Contains(column.HeaderText))
                {
                    column.Visible = false;
                }
                else
                {
                    column.Visible = true;
                }
            }
        }


        public void LoadData(WorkNode workNode){
            lblProjectName.Text = workNode.ProjectName;
            lblNodeName.Text = workNode.NodeName;
            lblNodeNum.Text = workNode.NodeNum;
            LblPidNum.Text = workNode.PidList;
            SessionDate.Value = workNode.SessionDate;
            TbxTechDescription.Text = workNode.TecDesc;
//            List<WorkNodeItem> tmp = Program.Workspace.GetAllWorkNodeItemsByNodeName(workNode.NodeName);
//            BindingList<WorkNodeItem> list = new BindingList<WorkNodeItem>(tmp);
//            dgvWorkArea.DataSource = list;
            _adviceCount = Program.Workspace.GetAdviceCountByNodeName(workNode.NodeName);
        }


        private void _cbxGuideWord_SelectedIndexChanged(object sender, EventArgs e){
         //   dgvWorkArea.CurrentCell.Value = _cbxGuideWord.Text;
        //    BindReasonColumnToolTips(dgvWorkArea.CurrentCell.Value.ToString());
        }

        private void BindReasonColumnToolTips(string guideWord){
            List<string> reasonTips = new List<string>();
            if (Program.Workspace.ResonList.ContainsKey(guideWord))
                reasonTips = Program.Workspace.ResonList[guideWord];
            string toolTips = null;
            foreach (string s in reasonTips){
                toolTips += (s + "\n");
            }
            dgvWorkArea.CurrentRow.Cells[2].ToolTipText = toolTips;
        //    dgvWorkArea.CurrentRow.Cells[5].ToolTipText = "1.渺茫(10000年1次)\n2.极少(1000年1次)\n3.偶尔(100年1次)\n4.较多(10年1次)\n5.频繁(每年超过1次)\n";
       //     dgvWorkArea.CurrentRow.Cells[6].ToolTipText = "1.*轻伤或刺激*泄漏至收集系统*停产<1天\n2.*误工伤害*泄漏在厂界内*停产<1周\n3.*残疾伤害*泄漏至厂界外*停产<1月\n4.*1人死亡*厂外人员伤残*停产<6月\n5.*多人死亡事故*厂外人员死亡*停产>6月\n";
       //     dgvWorkArea.CurrentRow.Cells[11].ToolTipText = "1.渺茫(10000年1次)\n2.极少(1000年1次)\n3.偶尔(100年1次)\n4.较多(10年1次)\n5.频繁(每年超过1次)\n";
        //    dgvWorkArea.CurrentRow.Cells[12].ToolTipText = "1.*轻伤或刺激*泄漏至收集系统*停产<1天\n2.*误工伤害*泄漏在厂界内*停产<1周\n3.*残疾伤害*泄漏至厂界外*停产<1月\n4.*1人死亡*厂外人员伤残*停产<6月\n5.*多人死亡事故*厂外人员死亡*停产>6月\n";
            string s1 = "1. "+Program.Workspace.project.RiskMatrix.RmR1 + "\n" + "2. "+Program.Workspace.project.RiskMatrix.RmR2 +
                       "\n" +"3. "+
                       Program.Workspace.project.RiskMatrix.RmR3 + "\n" + "4. "+Program.Workspace.project.RiskMatrix.RmR4 +
                       "\n" + "5. "+Program.Workspace.project.RiskMatrix.RmR5 + "\n";
            string l1 = "1.\n"+Program.Workspace.project.RiskMatrix.RmC1 + "\n" + "2.\n"+Program.Workspace.project.RiskMatrix.RmC2 +
                       "\n" +"3.\n"+
                       Program.Workspace.project.RiskMatrix.RmC3 + "\n" + "4.\n"+ Program.Workspace.project.RiskMatrix.RmC4 +
                       "\n" + "5.\n"+Program.Workspace.project.RiskMatrix.RmC5 + "\n";
            dgvWorkArea.CurrentRow.Cells[5].ToolTipText = l1;
            dgvWorkArea.CurrentRow.Cells[6].ToolTipText = s1;
            dgvWorkArea.CurrentRow.Cells[11].ToolTipText = l1;
            dgvWorkArea.CurrentRow.Cells[12].ToolTipText = s1;
        }

        private void dgvWorkArea_CurrentCellChanged(object sender, EventArgs e){
//            DataGridViewCell currentCell = dgvWorkArea.CurrentCell;
//            if (currentCell != null && currentCell.OwningColumn.Name.Equals("guideWord")){
//                Rectangle r = dgvWorkArea.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, true);
                //_cbxGuideWord.Text = currentCell.Value.ToString();
//                _cbxGuideWord.Size = r.Size;
//                _cbxGuideWord.Top = r.Top;
//                _cbxGuideWord.Left = r.Left;
//                _cbxGuideWord.Visible = true;
//                if(currentCell.Value != null){
//                    _cbxGuideWord.Text = currentCell.Value.ToString();
//                }
//            }
//            else{
//                _cbxGuideWord.Visible = false;
//            }
        }

        private void dgvWorkArea_CellEnter(object sender, DataGridViewCellEventArgs e){
            DataGridViewCell currentCell = dgvWorkArea.CurrentCell;
            if (currentCell.OwningColumn.Name.Equals("guideWord") || currentCell.OwningColumn.Name.Equals("recType")
                || currentCell.OwningColumn.Name.Equals("causes"))
            {
          //      SendKeys.Send("{F4}");
            }
        }

        private void dgvWorkArea_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e == null || e.Control == null)
                return;
            if(e.Control.GetType() == typeof(DataGridViewTextBoxEditingControl)){
                DataGridViewTextBoxEditingControl te = (DataGridViewTextBoxEditingControl)e.Control;
                te.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //建议追加 
                te.AutoCompleteSource = AutoCompleteSource.CustomSource;
                if(dgvWorkArea.CurrentCell.OwningColumn.Name.Equals("causes")){
                    //  te.AutoCompleteCustomSource.AddRange(new string[] { "你好", "哈哈" });
                List<string> remindReasonList = new List<string>();
                if (dgvWorkArea.CurrentRow == null || dgvWorkArea.CurrentRow.Cells[0].Value == null) {
                    return;
                }
                remindReasonList = Program.Workspace.ResonList[dgvWorkArea.CurrentRow.Cells[0].Value.ToString()];
                te.AutoCompleteCustomSource.AddRange(GetRemindReasonList(remindReasonList));
                   //  GetRemindReasonList(remindReasonList);
                }
            }
//            else if(e.Control is DataGridViewComboBoxEditingControl) {
//                (e.Control as DataGridViewComboBoxEditingControl).SelectedIndexChanged += new EventHandler(_cbxGuideWord_SelectedIndexChanged);
//                
//            }
            
        }

        private void WorkPage_SelectedIndexChanged(object sender, EventArgs e){
            int col = dgvWorkArea.CurrentCell.ColumnIndex;
            int row = dgvWorkArea.CurrentCell.RowIndex;
            if (dgvWorkArea.CurrentCell.OwningColumn.Name == "s1" && (dgvWorkArea.Rows[row].Cells[col + 1].Value != null)){
                dgvWorkArea.Rows[row].Cells[col+2].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col].Value.ToString(),
                                                               dgvWorkArea.Rows[row].Cells[col + 1].Value.ToString());
            }
//            if (dgvWorkArea.CurrentCell.OwningColumn.Name == "l1" && (dgvWorkArea.Rows[row].Cells[col - 1].Value != null) && (dgvWorkArea.Rows[row].Cells[col].Value != null))
//            {
//                dgvWorkArea.Rows[row].Cells[col + 1].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col - 1].Value.ToString(),
//                                                               dgvWorkArea.Rows[row].Cells[col].Value.ToString());
//            }
            if(dgvWorkArea.CurrentCell.OwningColumn.Name == "s2" && (dgvWorkArea.Rows[row].Cells[col + 1].Value != null)){
                dgvWorkArea.Rows[row].Cells[col + 2].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col].Value.ToString(),
                                                               dgvWorkArea.Rows[row].Cells[col + 1].Value.ToString());
            }
//            if (dgvWorkArea.CurrentCell.OwningColumn.Name == "l2" && (dgvWorkArea.Rows[row].Cells[col - 1].Value != null) && (dgvWorkArea.Rows[row].Cells[col].Value != null))
//            {
//                dgvWorkArea.Rows[row].Cells[col + 1].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col - 1].Value.ToString(),
//                                                               dgvWorkArea.Rows[row].Cells[col].Value.ToString());
//            }
        }

        private string[] GetRemindReasonList(List<string> reasonList){
            string[] result = new string[reasonList.Count];
            for (int i = 0; i < reasonList.Count; i++){
                result[i] = reasonList[i];
            }
            return result;
        }

        private void dgvWorkArea_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,e.RowBounds.Location.Y,dgvWorkArea.RowHeadersWidth - 4,e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,(e.RowIndex + 1).ToString(),dgvWorkArea.RowHeadersDefaultCellStyle.Font,rectangle,
                dgvWorkArea.RowHeadersDefaultCellStyle.ForeColor,TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        public Label LblProjectName{
            get { return lblProjectName; }
            set { lblProjectName = value; }
        }

        public Label LblNodeName{
            get { return lblNodeName; }
            set { lblNodeName = value; }
        }

        public Label LblNodeNum{
            get { return lblNodeNum; }
            set { lblNodeNum = value; }
        }

        public Label LblPidNum{
            get { return lblPidNum; }
            set { lblPidNum = value; }
        }

        public TextBox TbxTechDescription{
            get { return tbxTechDescription; }
            set { tbxTechDescription = value; }
        }

        public DateTimePicker SessionDate{
            get { return dateTimePicker1; }
            set { dateTimePicker1 = value; }
        }

        public DataGridView DgvWorkArea{
            get { return dgvWorkArea; }
            set { dgvWorkArea = value; }
        }

        private void dgvWorkArea_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {   
            int col = dgvWorkArea.CurrentCell.ColumnIndex;
            int row = dgvWorkArea.CurrentCell.RowIndex;
            dgvWorkArea.Rows[e.RowIndex].ErrorText = String.Empty;
            if (dgvWorkArea.CurrentCell.OwningColumn.Name.Equals("l1") && (dgvWorkArea.Rows[row].Cells[col - 1].Value != null))
            {
                dgvWorkArea.Rows[row].Cells[col + 1].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col - 1].Value.ToString(),
                                                                            dgvWorkArea.Rows[row].Cells[col].Value.ToString());
            }
            else if (dgvWorkArea.CurrentCell.OwningColumn.Name.Equals("l2") && (dgvWorkArea.Rows[row].Cells[col - 1].Value != null))
            {
                dgvWorkArea.Rows[row].Cells[col + 1].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col - 1].Value.ToString(),
                                                                           dgvWorkArea.Rows[row].Cells[col].Value.ToString());
            }
            else if (dgvWorkArea.CurrentCell.OwningColumn.Name.Equals("s1") && (dgvWorkArea.Rows[row].Cells[col + 1].Value != null))
            {
                dgvWorkArea.Rows[row].Cells[col + 2].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col].Value.ToString(),
                                                              dgvWorkArea.Rows[row].Cells[col + 1].Value.ToString());
            }
            else if(dgvWorkArea.CurrentCell.OwningColumn.Name == "s2" && (dgvWorkArea.Rows[row].Cells[col + 1].Value != null))
            {
                dgvWorkArea.Rows[row].Cells[col + 2].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col].Value.ToString(),
                                                               dgvWorkArea.Rows[row].Cells[col + 1].Value.ToString());
            }
            else if (dgvWorkArea.CurrentCell.OwningColumn.Name == "recommendations" && dgvWorkArea.CurrentCell.Value != null)
            {
                if (dgvWorkArea.Rows[row].Cells[col - 1].Value == null) {
                    _adviceCount++;
                    dgvWorkArea.Rows[row].Cells[col - 1].Value = lblNodeNum.Text + "--" + _adviceCount;
                }
            }
            else if (dgvWorkArea.CurrentCell.OwningColumn.Name == "guideWord" && dgvWorkArea.CurrentCell.Value != null)
            {
                BindReasonColumnToolTips(dgvWorkArea.CurrentCell.Value.ToString());
            }
        }

        private void dgvWorkArea_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 5 || e.ColumnIndex == 6 || e.ColumnIndex == 11 || e.ColumnIndex == 12) {
                int n = 0;
                if(int.TryParse(e.FormattedValue.ToString(),out n)) {
                    if(n < 0 || n > 5) {
                        dgvWorkArea.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "必须在1-5之间";
                    }
                    else {
                        dgvWorkArea.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                    }
                }
//                else if{
//                    dgvWorkArea.Rows[e.RowIndex].ErrorText = "请输入数字";//转换失败，类型都有问题
//                    e.Cancel = true;
//                }
            //    else if (dgvWorkArea.CurrentCell.Value != null)
                else 
                {
                      dgvWorkArea.Rows[e.RowIndex].ErrorText = "请输入数字";//转换失败，类型都有问题
                      e.Cancel = true;
                }
//                else {
//                    return;
//                }
            }
        }

        private void dgvWorkArea_DataError(object sender, DataGridViewDataErrorEventArgs e) {
            MessageBox.Show("日期格式必须为“月/日/年”,比如“3/21/2012”","日期格式错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            return;
        }

        private void addNewRow_Click(object sender, EventArgs e)
        {
//            DataGridViewRow row = new DataGridViewRow();
//            dgvWorkArea.Rows.Add(row);
         //   dgvWorkArea.Rows.Add();
            WorkNodeItem workNodeItem = new WorkNodeItem();
            _bindWorkNodeItems.Insert(dgvWorkArea.Rows.Count,workNodeItem);
            dgvWorkArea.Rows[dgvWorkArea.Rows.Count - 1].Selected = true;
            dgvWorkArea.CurrentCell = dgvWorkArea[1, dgvWorkArea.Rows.Count - 1];
        }

//        private void dgvWorkArea_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
//        {   
//            int col = dgvWorkArea.CurrentCell.ColumnIndex;
//            int row = dgvWorkArea.CurrentCell.RowIndex;
//            if (dgvWorkArea.CurrentCell.OwningColumn.Name == "recType" || dgvWorkArea.CurrentCell.OwningColumn.Name == "people")
//            {
//                dgvWorkArea.Rows[row].Cells[col - 1].Value = Program.Workspace.CalculateMatrix(dgvWorkArea.Rows[row].Cells[col - 3].Value.ToString(),
//                                                              dgvWorkArea.Rows[row].Cells[col - 2].Value.ToString());
//            }
//        }

        public void SaveWithoutRemider(){
            WorkNode workNode = Program.Workspace.GetWorkNodeByNodeName(lblNodeName.Text);
            if (workNode == null){
                return;
            }
            workNode.NodeName = lblNodeName.Text;
            workNode.NodeNum = lblNodeNum.Text;
            workNode.ProjectName = lblProjectName.Text;
            workNode.SessionDate = SessionDate.Value;
            workNode.PidList = LblPidNum.Text;
            workNode.TecDesc = TbxTechDescription.Text;
        }
    }
}
